import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store/index"

Vue.use(VueRouter)

function fn(msg, next) {
  let routerEnter = store.state.user.menus_url
  if (routerEnter.includes(msg)) {
    next()
  } else {
    next('/')
  }
}

export const secondRouter =
  [{
    path: "menu",
    meta: {
      title: "菜单管理"
    },
    beforeEnter: (to, from, next) => {
      fn("/menu", next)
    },
    component: () => import("../page/menu/menu.vue")
  }, {
    path: "banner",
    meta: {
      title: "轮播图管理"
    }, beforeEnter: (to, from, next) => {
      fn("/banner", next)
    },
    component: () => import("../page/banner/banner.vue")
  }, {
    path: "cate",
    meta: {
      title: "商品分类"
    },
    beforeEnter: (to, from, next) => {
      fn("/cate", next)
    },
    component: () => import("../page/cate/cate.vue")
  }, {
    path: "goods",
    meta: {
      title: "商品管理"
    },
    beforeEnter: (to, from, next) => {
      fn("/goods", next)
    },
    component: () => import("../page/goods/goods.vue")
  }, {
    path: "manage",
    meta: {
      title: "管理员管理"
    },
    beforeEnter: (to, from, next) => {
      fn("/manage", next)
    },
    component: () => import("../page/manage/manage.vue")
  }, {
    path: "member",
    meta: {
      title: "会员管理"
    },
    beforeEnter: (to, from, next) => {
      fn("/member", next)
    },
    component: () => import("../page/member/member.vue")
  }, {
    path: "role",
    meta: {
      title: "角色管理"
    },
    beforeEnter: (to, from, next) => {
      fn("/role", next)
    },
    component: () => import("../page/role/role.vue")
  }, {
    path: "seckill",
    meta: {
      title: "秒杀活动"
    },
    beforeEnter: (to, from, next) => {
      fn("/seckill", next)
    },
    component: () => import("../page/seckill/seckill.vue")
  }, {
    path: "specs",
    meta: {
      title: "商品规格"
    },
    beforeEnter: (to, from, next) => {
      fn("/specs", next)
    },
    component: () => import("../page/specs/specs.vue")
  }
  ]


const routes = [
  {
    path: "/login",
    component: () => import("../page/login/login.vue"),
  },
  {
    path: "/register",
    component: () => import("../page/register/register.vue"),
  },
  {
    path: "/",
    component: () => import("../page/index/index.vue"),
    children: [{
      path: "",
      component: () => import("../page/home/home.vue")
    },
    ...secondRouter
    ]
  }
]

const router = new VueRouter({
  routes
})


router.beforeEach((to, from, next) => {
  if (to.path == "/login" || to.path == "/register") {
    next()
    return
  }
  if (store.state.user.token) {
    next()
    return
  }
  next("/login")
})

export default router
